<template>
    <TopNav />

    <div class="main_wrap" style="background-color: #f5f5f5;">

        <div class="top">
            <div class="row">
                <div class="form_item">
                    <span class="label">订单编号：</span>
                    <el-input v-model="number" @click="handleClickNumber" readonly size="large"
                        style="width: 200px;" placeholder="请输入订单编号" />
                </div>
                <div class="form_item">
                    <span class="label">会&ensp;&ensp;员：</span>
                    <el-input v-model="memberPhoneNumber" @click="openPhoneNumberDialog" size="large"
                        style="width: 200px;" placeholder="请输入手机号" />
                </div>
                <div>
                    <el-radio-group v-model="onlineStatus" size="large">
                        <el-radio-button label="在线" value="0" />
                        <el-radio-button label="离线" value="1" />

                    </el-radio-group>
                </div>
            </div>
            <div class="row" style="padding-bottom: 10px;">
                <div class="form_item">
                    <span class="label">支付时间：</span>
                    <el-date-picker v-model="strTime" ref="startTimeRef" format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss" :clearable="false" type="datetime" placeholder="请选择日期"
                        size="large" style="width: 200px;" />
                </div>
                <div style="margin-right:10px;">至</div>
                <div class="form_item">

                    <el-date-picker v-model="endTime" ref="endTimeRef" format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss" :clearable="false" type="datetime" placeholder="请选择日期"
                        size="large" style="width: 200px;" />
                </div>

                <el-radio-group v-model="dayType" size="large" @change="changeDateTypes">
                    <el-radio-button label="今天" value="0" />
                    <el-radio-button label="昨天" value="1" />
                    <el-radio-button label="近7天" value="2" />
                </el-radio-group>
                <el-button size="large" type="success" @click="uploadAllOfflineOrder"
                    style="margin-left: 10px;">上传全部离线订单</el-button>
                <el-button size="large" type="primary" :icon="Search" @click="search">查询</el-button>
            </div>
        </div>
        <div class="main">

            <div class="my_table" ref="myTableRef">
                <el-table @current-change="handleCurrentChange" ref="singleTableRef" highlight-current-row
                    :header-cell-style="{ backgroundColor: '#f5f7fa', }" stripe :data="currentPageTableData">
                    <el-table-column type="index" :index="indexMethod" width="50" />
                    <el-table-column label="状态" min-width="70">
                        <template #default="scope">
                            <!-- 订单状态：0待支付、1、已完成、2、取消、9退款 -->
                            <span :class="`state_${scope.row.state}`">{{ scope.row.stateText }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="number" label="订单号" min-width="108" />

                    <el-table-column prop="memberPhoneNumber" label="会员" />
                    <el-table-column prop="receivableAmount" label="应收金额" />
                    <el-table-column prop="orderTime" label="下单时间" min-width="110" />

                    <el-table-column prop="offineID" label="离线单号" min-width="98" />
                    <el-table-column label="操作" width="88" style="padding: 0;">
                        <template #default="scope">
                            <el-button type="primary" @click="openDesc(scope.row)">
                                详情
                            </el-button>

                        </template>
                    </el-table-column>


                </el-table>
            </div>
            <div class="bottom">
                <!-- <div class="total">
                    <div>
                        <span>已完成订单应收金额：</span>
                        <span>{{ finishedTotalReceivableAmount }}元</span>
                    </div>
                    <div>
                        <span>应收金额：</span>
                        <span>{{ allTotalReceivableAmount }}元</span>
                    </div>
                </div> -->
                <div class="btns">
                    <el-button size="large" type="primary" @click="prev" :disabled="currentPage <= 1">上一页</el-button>
                    <el-button size="large" type="primary" @click="next"
                        :disabled="currentPage >= Math.ceil(pageTableData.flat().length / pageSize)">下一页</el-button>
                    <el-button size="large" type="success" :disabled="!currentRow" @click="printTicket">打印小票</el-button>
                </div>
            </div>
        </div>
        <!--打印wrap-->
        <div ref="domDiv" class="print_wrap" :class="(currentScaleType=='2'||currentScaleType=='3')?'tuoliduo':''"  v-if="currentRow && orderDesc"
            :style="{ paddingLeft: paperLeft, paddingRight: paperRight }">
            <div class="title">欢迎光临[一手店]</div>
            <div>重打小票</div>
            <div>单号：{{ currentRow.number || currentRow.offineID }}</div>
            <div>店铺：{{ currentRow.shopName }}</div>
            <div>电话：{{ userInfo.user_account }}</div>
            <div>收银：{{ userInfo.user_name }}</div>
            <div>时间：{{ currentRow.orderTime }}</div>
            <svg id="barcode"></svg>

            <div class="line"></div>
            <div class="flex">
                <div>商品/单位、数量</div>
                <div>金额</div>
            </div>
            <div class="item" v-for="item in orderDesc.orderDetailVos" :key="item.goodsID">
                <div><span class="gift" v-if="item.isGift">【赠】</span>{{ item.goodsName }}</div>
                <div class="flex">
                    <div>{{ item.retailPrice }} x{{ item.quantity }}</div>
                    <div>¥{{ item.payAmount }}</div>
                </div>
                <div class="discount" v-if="item.priceActivityID && item.priceTypeActivityDiscount > 0">(原价{{
                        item.originalPrice }}
                    已优惠{{
                        item.activityDiscount
                    }})</div>
            </div>
            <div class="line"></div>
            <div class="flex">
                <div>件数合计</div>
                <div>{{ currentRow.goodsQuantity }}</div>
            </div>
            <div class="flex">
                <div>订单金额</div>
                <div>¥{{ currentRow.originalAmount }}</div>
            </div>

            <div class="flex">
                <div>订单优惠</div>
                <div>¥{{ currentRow.discountAmount }}</div>
            </div>
            <div class="flex" v-if="couponDiscountPrice && couponDiscountPrice > 0">
                <div>优惠券抵扣</div>
                <div>¥{{ couponDiscountPrice }}</div>
            </div>
            <div class="flex">
                <div>应收金额</div>
                <div>¥{{ currentRow.receivableAmount }}</div>
            </div>
            <div class="line"></div>
            <div>支付方式</div>
            <div class="flex" v-for="item in orderDesc.orderPayInfoVos" :key="item.payType">
                <div>{{ item.payTypeText }}</div>
                <div>¥{{ item.payAmount }}</div>
            </div>
            <div class="line"></div>
            <div>多谢惠顾，欢迎下次光临</div>
            <div>客服电话：4006365999</div>
            <div class="margin_bottom_placeholder"></div>
        </div>

        <!--退款单wrap-->

        <div ref="refundDomDiv" class="print_wrap" :class="(currentScaleType=='2'||currentScaleType=='3')?'tuoliduo':''" v-if="currentRow && orderDesc && refundTicketInfo"
            :style="{ paddingLeft: paperLeft, paddingRight: paperRight }">
            <div class="title">欢迎光临[一手店]</div>

            <div class="flex">单号：{{ currentRow.number || currentRow.offineID }}</div>
            <div class="flex">店铺：{{ currentRow.shopName }}</div>
            <div class="flex">电话：{{ userInfo.user_account }}</div>
            <div class="flex">收银：{{ userInfo.user_name }}</div>
            <div class="flex">时间：{{ currentRow.orderTime }}</div>
            <svg id="barcode"></svg>

            <div class="line"></div>
            <div class="flex">
                <div>商品/单位、数量</div>
                <div>金额</div>
            </div>

            <div class="item" v-for="item in refundTicketInfo.refundGoodsAddDtos" :key="item.id">

                <div><span class="gift" v-if="item.isGift">【赠】</span>{{ item.goodsName }}</div>
                <!--数量单位-->
                <div class="flex" v-if="item.isQuantityUnit === '1'">
                    <div>{{ roundNumber(NP.divide(item.payAmount, item.originalTotalQuantity)) }} x {{ item.quantity }}
                    </div>
                    <div>¥{{ roundNumber(NP.times(roundNumber(NP.divide(item.payAmount,
                        item.originalTotalQuantity)), item.quantity)) }}</div>
                </div>
                <!--重量单位-->
                <div class="flex" v-else>

                    <div>{{ roundNumber(NP.divide(item.payAmount, item.originalTotalQuantity)) }} x {{ item.quantity }}
                    </div>
                    <div>¥{{ item.payAmount }}</div>
                </div>
            </div>



            <div class="line"></div>
            <!-- <div class="flex">
                <div>件数合计</div>
                <div>{{ refundTicketInfo.number }}</div>
            </div> -->
            <div class="flex">
                <div>订单金额</div>
                <div>-¥{{ getSumRefundPrice(refundTicketInfo.refundGoodsAddDtos) }}</div>
            </div>


            <!-- <div class="flex" v-if="refundTicketInfo.couponDiscountPrice">
                <div>优惠券抵扣</div>
                <div>-¥{{ refundTicketInfo.couponDiscountPrice }}</div>
            </div>
            <div class="flex">
                <div>应收金额</div>
                <div>-¥{{ NP.minus(getSumRefundPrice(refundTicketInfo.refundGoodsAddDtos)) }}</div>
            </div> -->
            <div class="line"></div>
            <div>支付方式</div>

            <template v-if="orderDesc.orderPayInfoVos.length == 1">
                <div class="flex">
                    <div>{{ orderDesc.orderPayInfoVos[0].payTypeText }}</div>
                    <div>-¥{{ NP.minus(getSumRefundPrice(refundTicketInfo.refundGoodsAddDtos)) }}</div>
                </div>
            </template>
            <template v-else>
                <div class="flex" v-for="item in orderDesc.orderPayInfoVos" :key="item.payType">
                    <div>{{ item.payTypeText }}</div>
                    <div>-¥{{ item.payAmount }}</div>
                </div>
            </template>

            <div class="line"></div>
            <div>多谢惠顾，欢迎下次光临</div>

            <div class="margin_bottom_placeholder"></div>
        </div>
    </div>

    <!--搜索键盘-->
    <SearchKeyboard keyboardContainerClass="orderquery_ordernumber_id" v-model="isShowSearchKeyboard" title="请输入订单编号"
        @onChange="onSearchKeyboardChange" class="custom_search_class">

    </SearchKeyboard>
    <!--会员手机号键盘-->
    <PhoneKeyboard ref="phoneKeyboardRef" v-model="isShowPhoneKeyboard"
        keyboardContainerClass="orderquery_phonenumber_id" title="请输入手机号" :inputVal="memberPhoneNumber"
        @onConfirmPhone="confirmPhone" class="custom_phone_class" />


    <!--订单详情-->
    <el-dialog fullscreen v-model="orderDescDialogVisible"  class="order_desc_dialog" title="订单详情" width="800">
        <el-descriptions size="large" title="" v-if="currentRow">
            <el-descriptions-item label="订单号">{{ currentRow.number }}</el-descriptions-item>
            <el-descriptions-item label="离线单号">{{ currentRow.offineID }}</el-descriptions-item>
            <el-descriptions-item label="会员">{{ currentRow.memberPhoneNumber }}</el-descriptions-item>
            <el-descriptions-item label="应收金额">{{ currentRow.receivableAmount }}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ currentRow.orderTime }}</el-descriptions-item>
            <el-descriptions-item label="件数">{{ currentRow.goodsQuantity }}</el-descriptions-item>
        </el-descriptions>

        <el-divider style="margin:0" />
        <div class="table_top">
            <div class="title">商品信息</div>
            <div v-if="orderDesc.orderDetailVos.length>2">
                <div class="paginate_btns">
                    <el-button size="large" :disabled="goodsCurrentPage <= 1" @click="goodsScrollUp">上一页</el-button>
                    <div>第{{ goodsCurrentPage }}页</div>
                    <el-button size="large" :disabled="goodsCurrentPage >= Math.ceil(orderDesc.orderDetailVos.length / goodsPageSize)"
                        @click="goodsScrollDown">下一页</el-button>
                    
                </div>
            </div>
        </div>

        <el-table ref="goodsTableRef" :max-height="goodsPageSize * 40 + 40" border show-overflow-tooltip :header-cell-style="{ backgroundColor: '#f5f7fa', }" stripe
            :data="orderDesc.orderDetailVos" style="height: 100%;">
            <el-table-column type="index" width="50" />
            <el-table-column  label="商品">
                <template #default="scope">
                    <el-tag type="danger" size="small" effect="dark" v-if="scope.row.isGift==1"
                                                disable-transitions>赠</el-tag>  {{ scope.row.goodsName }}
                 </template>
            </el-table-column>
            <el-table-column prop="payAmount" label="小计" width="90" />
            <el-table-column prop="quantity" label="数(重)量" width="90" />
        </el-table>
       
        <div class="table_top" >
            <div class="title">付款信息</div>
            <div v-if="orderDesc.orderPayInfoVos.length>2">
                <div class="paginate_btns">
                    <el-button size="large" :disabled="payTypeCurrentPage <= 1" @click="payTypeScrollUp">上一页</el-button>
                    <div>第{{ payTypeCurrentPage }}页</div>
                    <el-button size="large" :disabled="payTypeCurrentPage >= Math.ceil(orderDesc.orderPayInfoVos.length / payTypePageSize)"
                        @click="payTypeScrollDown">下一页</el-button>
                    
                </div>
            </div>
        </div>
        
        <el-table ref="payTypeTableRef" border :max-height="payTypePageSize * 40 + 40" :header-cell-style="{ backgroundColor: '#f5f7fa', }" stripe :data="orderDesc.orderPayInfoVos" style="height: 100%;">
            <el-table-column type="index" width="50" />
            <el-table-column prop="payTypeText" label="支付方式" />
            <el-table-column prop="payAmount" label="金额" />

        </el-table>
        <template #footer>
            <div class="dialog-footer" v-if="currentRow">
                <el-button size="large" type="danger" @click="handleRefound"
                    v-if="currentRow.state === '1' && currentRow.number">
                    退款
                </el-button>
                <el-button size="large" type="success" @click="handleRefresh" v-if="currentRow.state === '0'">
                    刷新
                </el-button>
                <el-button size="large" type="primary" @click="orderDescDialogVisible = false">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!--离线订单上传dialog-->
    <el-dialog v-model="isShowUploadDialog" class="upload_dialog" title="离线订单上传" width="800">
        <div class="upload_dialog_main">
            正在上传第 <span>{{ currentUploadIndex }}</span> 笔离线订单...
        </div>
    </el-dialog>
    <!--退款dialog-->
    <el-dialog v-model="isShowRefoundDialog" class="refund_dialog" title="退款" width="800">
        <div class="refund_dialog_main">
           
            <el-table ref="refundTableRef" show-overflow-tooltip border :max-height="(refundPageSize * 40 + 40)"
                :header-cell-style="{ backgroundColor: '#f5f7fa', }" stripe :data="refundTableData"
                @selection-change="handleRefoundGoodsSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" label="序" width="55" />
                <el-table-column prop="goodsName" label="商品" />
                <el-table-column label="单价" width="90">
                    <template #default="scope">
                        {{ roundNumber(NP.divide(scope.row.payAmount, scope.row.quantity)) }}
                    </template>
                </el-table-column>
                <el-table-column prop="quantity" label="销售量" width="90" />
                <el-table-column prop="payAmount" label="实收金额" width="90" />
                <el-table-column label="退货量" width="100" style="padding:0">
                    <template #default="scope">
                        <div v-if="scope.row.isQuantityUnit === '1'">
                            <MyInput @click="openRefoundCountKeyboard(scope.row)" placeholder="请输入退货量"
                                :innerText="scope.row.refundQuantity" class="item" style="width: 100%;height:36px" />
                        </div>
                        <div v-else>
                            {{ scope.row.quantity }}
                        </div>

                    </template>

                </el-table-column>
                <el-table-column label="退货金额" width="90">
                    <template #default="scope">
                        <!--数量单位-->
                        <span v-if="scope.row.isQuantityUnit === '1'">
                            {{
                        roundNumber(NP.times(roundNumber(NP.divide(scope.row.payAmount, scope.row.quantity)), scope.row.refundQuantity))
                    }}
                        </span>
                        <span v-else>
                            {{ scope.row.payAmount }}
                        </span>
                    </template>

                </el-table-column>
            </el-table>
        </div>
        <template #footer>
            <div class="refund-dialog-footer">
                <div class="left">
                    <el-button @click="scrollUp" size="large" :disabled="refundPageNo <= 1">上一页</el-button>
                    <span>第{{ refundPageNo }}页</span>
                    <el-button @click="scrollDown" size="large"
                        :disabled="refundPageNo >= Math.ceil(refundTableData.length / refundPageSize)">下一页</el-button>
                </div>
                <div class="right">
                    <el-button size="large" type="danger" @click="handleRefoundOrder('0')">
                        整单退款
                    </el-button>
                    <el-button size="large" type="warning" @click="handleRefoundOrder('1')">
                        部分退款
                    </el-button>
                </div>
            </div>
        </template>
    </el-dialog>

    <!--数字键盘(输入退货量)-->
    <CountKeyboard class="orderquery_count_keyboard" placeholder="请输入退货量" v-model="isShowRefoundCountKeyboard"
        :isShowPoint="false" keyboardContainerClass="orderquery_count_container" @onConfirm="onConfirmRefoundCount"
        ref="orderQueryCountKeboardRef" title="请输入退货量" />

    <el-dialog v-model="isShowRefundOrderConfirmDialog" class="refund_dialog" title="提示" width="800">
        <div class="refund_dialog_main">
            确认退款？
        </div>

        <template #footer>
            <div class="dialog-footer" v-if="currentRow">

                <el-button size="large" type="default" @click="isShowRefundOrderConfirmDialog = false">
                    取消
                </el-button>
                <el-button size="large" type="primary" @click="confirmRefoundOrder">
                    确认
                </el-button>
            </div>
        </template>

    </el-dialog>
</template>


<script setup lang='ts'>
// @ts-nocheck
import CountKeyboard from '@renderer/components/CountKeyboard.vue'
import domtoimage from 'dom-to-image'; //dom转图片
import JsBarcode from 'jsbarcode'; //条形码
import { createOrder } from '@renderer/api/shopsale'
import { orderQuery, getOrderDesc, refreshOrder, refundOrder } from '@renderer/api/orderquery'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { onMounted, ref, watch, watchEffect, computed, nextTick, onBeforeUnmount } from 'vue'
import { getDateTimeString,debounce } from '@renderer/utils'
import SearchKeyboard from '@renderer/components/SearchKeyboard.vue'
import PhoneKeyboard from '@renderer/components/PhoneKeyboard.vue'
import { useUserStore } from '@renderer/store/user'
import { storeToRefs } from 'pinia'
import NP from "number-precision";

const number = ref('')
const memberPhoneNumber = ref('')
const onlineStatus = ref('0')
const tableData = ref([])
const pageTableData = ref([]) //分页后的数据
const pageSize = ref(0) //每页条数
const currentPage = ref(1)
const currentRow = ref()
const userStore = useUserStore()
const { userInfo, shopInfo, paperLeft, paperRight,currentScaleType,currentTime} = storeToRefs(userStore)
const saleOrganizationID = userInfo.value.user_organizationId
const saleOrganizationName = shopInfo.value.organizationName
const myTableRef = ref()
const singleTableRef = ref()
const orderDescDialogVisible = ref(false)
const orderDesc = ref()
let domDiv = ref()
let refundDomDiv = ref()
const refundTicketInfo = ref(null)
const currentSearchOnlineStatus = ref('0') //搜索完成后的状态
const currentUploadIndex = ref(1)
const isShowUploadDialog = ref(false)
const isShowRefoundDialog = ref(false)
const isShowRefoundCountKeyboard = ref(false)
const refundTableData = ref([])
//当前退款行
const currentRefoundRow = ref(null)
//当前退款选中行
const currentRefoundGoodsSelectionsRows = ref([])
const refundTableRef = ref()
const refundPageNo = ref(1)
const refundPageSize = ref(5)
const phoneKeyboardRef = ref()
const currentFundType = ref('0') //'0' 整单退 / '1' 部分退款
const isShowRefundDialog = ref(false)
const isShowRefundOrderConfirmDialog = ref(false) //退款确认弹窗
const goodsPageSize = ref(2)
const goodsCurrentPage = ref(1)
const goodsTableRef = ref()

const payTypePageSize = ref(2)
const payTypeCurrentPage = ref(1)
const payTypeTableRef = ref()

onMounted(() => {
    let tableHeight = myTableRef.value.offsetHeight
    let singleRowHeight = 49 //每行高度
    pageSize.value = Math.floor(tableHeight / singleRowHeight) - 1 //每页最多显示行数(-1 是减去header)
    console.log('onMounted')
    window.addEventListener('keydown', handleKeyDown);
})
onBeforeUnmount(() => {
    console.log('onBeforeUnmount')
    window.removeEventListener('keydown', handleKeyDown);
})
let barcodeBuffer = '';
const handleKeyDown = (event) => {
    // 阻止默认行为，避免按钮聚焦
    event.preventDefault();
    // 忽略修饰键
    if (event.key.length > 1 && event.key !== 'Enter') return;

    // 如果当前按键是回车键（扫码枪通常以回车键结束）
    if (event.key === 'Enter') { //如果是Enter表示扫码完成
       
        handleBarCode(barcodeBuffer.trim())

        barcodeBuffer = '';
        return
    } else {
        barcodeBuffer += event.key;
    }

}
const handleBarCode = debounce(function (barcodeBuffer) {
    // console.log(barcodeBuffer)
    if(barcodeBuffer.length<16){
        ElMessage({
            message:'该条码无效',
            type:'error'
        })
        return 
    }else{
        
        number.value = barcodeBuffer
    }
})


function handleClickNumber(){
    number.value = ''
    isShowSearchKeyboard.value = true
}

function handleRefound() {

    let orderTime = new Date(currentRow.value.orderTime).getTime()
    
    //订单退款不能超过7天
    if(isMoreThanXDays(currentTime.value,orderTime,7)){
        ElMessage({
            message: '订单退款不能超过7天',
            type: 'warning',
        })
        return 
    }

    
    refundTableData.value = JSON.parse(JSON.stringify(orderDesc.value.orderDetailVos.map(item => ({ ...item, refundQuantity: item.quantity }))))
    isShowRefoundDialog.value = true
}
function openRefoundCountKeyboard(row) {
    if (row.isQuantityUnit != '1') {
        ElMessage({
            message: `称重商品不能修改退货量`,
            type: 'error'
        })
        return false
    }
    currentRefoundRow.value = row
    isShowRefoundCountKeyboard.value = true
}

function onConfirmRefoundCount(count) {
 
    if (count * 1 > currentRefoundRow.value.quantity * 1) {

        ElMessage({
            message: `退货量不能大于${currentRefoundRow.value.refundQuantity * 1}`,
            type: 'error'
        })
        return false
    }
    currentRefoundRow.value.refundQuantity = count
   // console.log(currentRefoundRow.value)
    isShowRefoundCountKeyboard.value = false
}

function openPhoneNumberDialog() {

    isShowPhoneKeyboard.value = true
    //console.log(memberPhoneNumber.value)
    phoneKeyboardRef.value && phoneKeyboardRef.value.setKeyboardInput(memberPhoneNumber.value)

}

//获得退款选中商品行
function handleRefoundGoodsSelectionChange(vals) {
    //console.log(vals)
    currentRefoundGoodsSelectionsRows.value = vals
}


function handleRefoundOrder(type) {
    currentFundType.value = type
    if (type === '1') {
        const { orderPayInfoVos } = orderDesc.value
        if (orderPayInfoVos.length > 1) {
            ElMessage({
                message: '多种支付方式,不能部分退款',
                type: 'error'
            })
            return false

        }
        if (currentRefoundGoodsSelectionsRows.value.length <= 0) {
            ElMessage({
                message: '请选择退款商品',
                type: 'error'
            })
            return false
        }



    }else{
        //整单退款新增判断 2025/04/29
        // console.log(refundTableData.value)
        // console.log(orderDesc.value.orderDetailVos)
        let flag = false
        for (let i = 0; i < refundTableData.value.length; i++) {
            if (refundTableData.value[i].refundQuantity != orderDesc.value.orderDetailVos[i].quantity) {
                ElMessage({
                    message: '退货量与原订单数量不一致，请选择部分退款',
                    type: 'error',
                    duration:5000
                })
                flag = true
                break
            }
        }
        if(flag){
            return false
        }

        //整单退款新增判断 2025/04/29 end
    }

    isShowRefundOrderConfirmDialog.value = true


}

async function confirmRefoundOrder() {
    const type = currentFundType.value
    let isAllRefund = 'y'
    const { id: orderID } = currentRow.value
    const { orderDetailVos, orderPayInfoVos } = orderDesc.value
    //console.log(orderDesc.value)
    let refundGoodsAddDtos
    if (type === '0') {
        // console.log('整单退款')
        // console.log(refundTableData.value)
        refundGoodsAddDtos = refundTableData.value.map(item => {
            let activityDiscount = item.isQuantityUnit === '1' ? NP.times(item.activityDiscount ? item.activityDiscount : 0, NP.divide(item.refundQuantity, item.quantity)) : item.activityDiscount
            let couponDiscount = item.isQuantityUnit === '1' ? NP.times(item.couponDiscount ? item.couponDiscount : 0, NP.divide(item.refundQuantity, item.quantity)) : item.couponDiscount
            return {
                ...item,
                orderDetailID: item.id,//订单详情ID 
                number: item.isQuantityUnit == '1' ? item.refundQuantity : 1,//订单件数
                originalTotalQuantity: item.quantity,
                quantity: item.refundQuantity,//退货数量
                refundAmount: item.isQuantityUnit === '1' ? NP.round(NP.times(NP.divide(item.payAmount, item.quantity), item.refundQuantity), 2) : item.payAmount,//退货金额 = 实收金额/销售量 * 退货量 四舍五入保留两位小数
                activityDiscount,
                couponDiscount,
                discountAmount: NP.plus(activityDiscount, couponDiscount)

            }
        })
       // console.log(refundGoodsAddDtos)


    } else {

        if (orderPayInfoVos.length > 1) {
            ElMessage({
                message: '多种支付方式,不能部分退款',
                type: 'error'
            })
            return false

        }
        isAllRefund = 'n'


        if (refundTableData.value.length === currentRefoundGoodsSelectionsRows.value.length) { //如果选择的是部分退款 并且退款总商品种类=勾选商品种类
            //如果每一行商品的退货量都等于部分退款的退货量则是整单退款
            let isEquals = true //比较是否完全相同
            for (let i = 0; i < refundTableData.value.length; i++) {
                if (refundTableData.value[i].quantity !== currentRefoundGoodsSelectionsRows.value[i].refundQuantity) {
                    isEquals = false
                    break
                }
            }

            if (isEquals) { //整单退款
                isAllRefund = 'y'
            }

        }


        refundGoodsAddDtos = currentRefoundGoodsSelectionsRows.value.map(item => {
            let activityDiscount = item.isQuantityUnit === '1' ? NP.times(item.activityDiscount ? item.activityDiscount : 0, NP.divide(item.refundQuantity, item.quantity)) : item.activityDiscount
            let couponDiscount = item.isQuantityUnit === '1' ? NP.times(item.couponDiscount ? item.couponDiscount : 0, NP.divide(item.refundQuantity, item.quantity)) : item.couponDiscount

            return {
                ...item,
                originalTotalQuantity: item.quantity,
                orderDetailID: item.id,//订单详情ID 
                number: item.isQuantityUnit == '1' ? item.refundQuantity : 1,//订单件数
                quantity: item.refundQuantity,//退货数量
                refundAmount: item.isQuantityUnit === '1' ? NP.round(NP.times(NP.divide(item.payAmount, item.quantity), item.refundQuantity), 2) : item.payAmount,//退货金额 = 实收金额/销售量 * 退货量 四舍五入保留两位小数
                activityDiscount,
                couponDiscount,
                discountAmount: NP.plus(activityDiscount, couponDiscount)
            }
        })
       // console.log(refundGoodsAddDtos)
    }



    //console.log(saleOrganizationName)
    const reqData = {
        saleOrganizationID,
        orderID,
        saleOrganizationName,
        isAllRefund,
        refundGoodsAddDtos
    }

    try {


        const { msg } = await refundOrder(reqData)
        ElMessage({
            message: msg,
            type: 'success'
        })
        refundTicketInfo.value = reqData
        nextTick(() => {

            refundPrintTicket()


        })



        isShowRefundOrderConfirmDialog.value = false
        isShowRefoundDialog.value = false
        orderDescDialogVisible.value = false
        //重新查询订单
        search()

        //打印退款单 TODO
    } catch (error) {
        console.log(error)
    }
}
//四舍五入(保留2位小数)
function roundNumber(number) {
    return NP.round(number, 2)
}

//计算退款总金额
function getSumRefundPrice(list) {
   // console.log(list)

    // <!--数量单位-->
    //             <div class="flex" v-if="item.isQuantityUnit==='1'"> 
    //                 <div>{{roundNumber(NP.divide(item.payAmount, item.originalTotalQuantity)) }} x {{ item.quantity }}</div>
    //                 <div>¥{{ roundNumber(roundNumber(NP.divide(item.payAmount, item.originalTotalQuantity)),item.quantity) }}</div>
    //             </div>
    //          <!--重量单位-->
    //          <div class="flex" v-else> 
    //                 <div>{{roundNumber(NP.divide(item.payAmount,item.originalTotalQuantity)) }} x {{ item.quantity }}</div>
    //                 <div>¥{{ item.payAmount }}</div>
    //             </div>


    return list.reduce((prev, currentVal) => {
        let isQuantityUnit = currentVal.isQuantityUnit
        if (isQuantityUnit === '1') {

            return NP.plus(prev, roundNumber(NP.times(roundNumber(NP.divide(currentVal.payAmount, currentVal.originalTotalQuantity)), currentVal.quantity)))
        } else {
            return NP.plus(prev, currentVal.payAmount)
        }
    }, 0)
}

// 向下滚动
const scrollDown = () => {

    refundPageNo.value++

    refundTableRef.value.setScrollTop((refundPageNo.value - 1) * (refundPageSize.value * 40))
};
const scrollUp = () => {

    refundPageNo.value--
    refundTableRef.value.setScrollTop((refundPageNo.value - 1) * (refundPageSize.value * 40))
};


//分页
function paginateData(data, pageSize) {
    const pages = [];
    for (let i = 0; i < data.length; i += pageSize) {
        pages.push(data.slice(i, i + pageSize));
    }
    return pages;
}

function prev() {
    if (currentPage.value <= 1) return
    currentPage.value--
}
function next() {
    
    currentPage.value++
}
//计算序号
function indexMethod(index) {
    return (currentPage.value - 1) * pageSize.value + index + 1
}

//切换选中行
const handleCurrentChange = (val) => {
   // console.log(val)
    currentRow.value = val
}

//查询详情
async function getDesc(row) {

    const shopID = shopInfo.value.shopID
    const orderID = row.id
    try {
        const { data } = await getOrderDesc(saleOrganizationID, shopID, orderID)
        orderDesc.value = data
       // console.log(data)
    } catch (error) {
        console.log(error)
    }

}

//查看详情
async function openDesc(row) {
    currentRow.value = row
    if (currentSearchOnlineStatus.value === '0') {
        await getDesc(row)
    } else {
        orderDesc.value = row.desc
    }

    orderDescDialogVisible.value = true
   
}

//计算优惠券抵扣，各商品抵扣综合
const couponDiscountPrice = computed(() => {

    if (!orderDesc.value) return 0
    return orderDesc.value.orderDetailVos.reduce((prev, currentVal) => {
        return NP.plus(prev, currentVal.couponDiscount)
    }, 0)
})

//刷新
async function handleRefresh() {
    const { id: orderID, number } = currentRow.value
    
    const reqData = {
        saleOrganizationName,
        saleOrganizationID,
        orderID,
        tradeNO: '',
        shopID: shopInfo.value.shopID,
        accountType: '',
        number
    }
    const electronicRow = orderDesc.value.orderPayInfoVos.find(item => item.payType === 'EP') //找到电子支付的支付方式行
    if (electronicRow) {
        reqData.tradeNO = electronicRow.tradeNO
        reqData.accountType = electronicRow.accountType
    }
    try {
        const { msg } = await refreshOrder(reqData)
        ElMessage({
            message: msg,
            type: 'success'
        })
        orderDescDialogVisible.value = false
        //重新查询订单
        search()
    } catch (error) {
        console.log(error)
    }

}


//dom-to-image
function getDomToImg(node,) {
    domtoimage.toPng(node,)
        .then(function (dataUrl) {
           // console.log(dataUrl)
            const base64ImageData = dataUrl.replace(/^data:image\/png;base64,/, '');
            window.electron.ipcRenderer.invoke('send-print', { data: base64ImageData })
        })
        .catch(function (error) {
            console.log('oops, something went wrong!', error);
        });
}



//打印小票
async function printTicket() {
    //console.log(currentRow.value)

    if (currentRow.value) {
        try {
            await getDesc(currentRow.value)
            JsBarcode("#barcode", currentRow.value.number, {
                format: "CODE128", // 可以选择其他格式，如 "EAN13"、"UPC" 等
                lineColor: "#000", // 条形码颜色
                width: 2.5,          // 条宽
                height: 100,       // 条高
                displayValue: false // 是否显示数值
            });
            nextTick(() => {
                getDomToImg(domDiv.value)
            })

        } catch (error) {
            console.log(error)
        }

    } else {

       // console.log('请选择订单')
    }
}

//退款单打印小票
async function refundPrintTicket() {
    if (currentRow.value) {
        try {

            JsBarcode("#barcode", currentRow.value.number, {
                format: "CODE128", // 可以选择其他格式，如 "EAN13"、"UPC" 等
                lineColor: "#000", // 条形码颜色
                width: 2.5,          // 条宽
                height: 120,       // 条高
                displayValue: false // 是否显示数值
            });

            getDomToImg(refundDomDiv.value)


        } catch (error) {
            console.log(error)
        }

    } else {

        //console.log('请选择订单')
    }
}

//已完成订单应收金额合计
const finishedTotalReceivableAmount = computed(() => {
    return tableData.value.filter(item => item.state === '1').reduce((prev, currentVal) => {
        return NP.plus(prev, currentVal.receivableAmount)
    }, 0)
})
//全部订单应收金额合计
const allTotalReceivableAmount = computed(() => {
    return tableData.value.reduce((prev, currentVal) => {
        //console.log(currentVal)
        return NP.plus(prev, currentVal.receivableAmount)
    }, 0)
})

//当前页数据
const currentPageTableData = computed(() => {
    return pageTableData.value[currentPage.value - 1] || []
})

const dayType = ref('0')

//今天、昨天、近7天切换
function changeDateTypes(val) {
    if (val === '0') {
        setToday()
    } else if (val === '1') {
        setYesterday()
    } else if (val === '2') {
        setLastWeek()
    }
}

//根据日期设置按钮组选中状态
function setBtnsTypeByDate() {
    const todayStr = getDateTimeString(new Date().getTime())
    const yesterdayStr = getDateTimeString(new Date().getTime() - 3600 * 1000 * 24)
    const lastWeekDayStr = getDateTimeString(new Date().getTime() - 3600 * 1000 * 24 * 6)
    if (strTime.value === todayStr + ' 00:00:00' && endTime.value === todayStr + ' 23:59:59') {
        dayType.value = '0'
    } else if (strTime.value === yesterdayStr + ' 00:00:00' && endTime.value === yesterdayStr + ' 23:59:59') {
        dayType.value = '1'
    } else if (strTime.value === lastWeekDayStr + ' 00:00:00' && endTime.value === todayStr + ' 23:59:59') {
        dayType.value = '2'
    } else {
        dayType.value = ''
    }
}

const today = getDateTimeString(new Date().getTime())
const strTime = ref(today + ' 00:00:00')
const endTime = ref(today + ' 23:59:59')

//const endDefaultTime = ref('2024-09-08 23:59:59') //默认时间23:59:59 前面的日期没有用

const startTimeRef = ref()
const endTimeRef = ref()

const isShowSearchKeyboard = ref(false)
function onSearchKeyboardChange(val) {
    number.value = val
}

const isShowPhoneKeyboard = ref(false)
function confirmPhone(val) {
   // console.log(val)
    memberPhoneNumber.value = val
}

//日期改变后直接关闭弹窗
watch(strTime, () => {
    startTimeRef.value.handleClose()
    setBtnsTypeByDate()
})
watch(endTime, () => {
    endTimeRef.value.handleClose()
    setBtnsTypeByDate()
})

function isMoreThanXDays(date1, date2,x) {
      //是否超过x天
      // 确保date1在date2之前，如果不是，则交换它们
      if (date1 > date2) {
        let temp = date1;
        date1 = date2;
        date2 = temp;
      }

      // 将日期转换为时间戳（毫秒）
      let timeDiff = new Date(date2).getTime() - new Date(date1).getTime();

      // 将毫秒转换为天数
      let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

      // 判断天数是否大于x
      return diffDays > x;
 }
function search() {
    if (strTime.value && endTime.value && new Date(endTime.value).getTime() < new Date(strTime.value).getTime()) {

        endTime.value = ''
        ElMessage({
            message: '结束时间不能小于开始时间',
            type: 'warning',
        })
        return
    }
    if(isMoreThanXDays(strTime.value,endTime.value,7)){
        ElMessage({
            message: '单次查询日期最长跨度为7天',
            type: 'warning',
        })
        return 
    }
    currentPage.value = 1

    // if(!isWithin7Days(strTime.value,endTime.value)){
    //     ElMessage({
    //         message: '日期跨度不能超过7天',
    //         type: 'warning',
    //     })
    //     return
    // }


    queryOrder()
}
async function queryOrder() {
    currentSearchOnlineStatus.value = onlineStatus.value

    const shopID = shopInfo.value.shopID

    const reqData = {
        saleOrganizationID,
        shopID,
        memberPhoneNumber: memberPhoneNumber.value,
        number: number.value,
        strTime: strTime.value,
        endTime: endTime.value
    }
   // console.log(reqData)
    if (onlineStatus.value === '1') { //离线模式
      //  console.log('离线模式')

        try {
            const data = await window.electron.ipcRenderer.invoke('select-order', { startTime: reqData.strTime, endTime: reqData.endTime, offineID: number.value })
         //   console.log(data)
            let mapData = data.map(item => {
                return {
                    ...item,
                    stateText: '已完成',
                    state: '1',//离线订单默认已完成
                    desc: {
                        orderDetailVos: JSON.parse(item.orderDetailAddDtos),
                        orderPayInfoVos: JSON.parse(item.orderPayDto).orderPayAddDtos
                    }
                }
            })
            tableData.value = mapData

            pageTableData.value = paginateData(mapData, pageSize.value)

           // console.log(tableData.value)
        } catch (error) {
            console.log(error)
        }


        return
    } else {

    }


    const { data } = await orderQuery(reqData)
   
    tableData.value = data
    //console.log(pageSize.value)
    pageTableData.value = paginateData(data, pageSize.value)
   // console.log(pageTableData.value)
    singleTableRef.value!.setCurrentRow(tableData.value[0])
}
function setToday() { //将日期设为今天
    const dateString = getDateTimeString(new Date().getTime())
    strTime.value = dateString + ' 00:00:00'
    endTime.value = dateString + ' 23:59:59'

}

function setYesterday() { //将日期设为昨天昨天
    const dateString = getDateTimeString(new Date().getTime() - 3600 * 1000 * 24)
    strTime.value = dateString + ' 00:00:00'
    endTime.value = dateString + ' 23:59:59'

}

//是否超过7天
function isWithin7Days(startDate, endDate) {
    // 将日期字符串转换为 Date 对象
    const start = new Date(startDate);
    const end = new Date(endDate);

    // 计算时间差（以毫秒为单位）
    const timeDifference = end - start;

    // 将毫秒转换为天数
    const daysDifference = timeDifference / (1000 * 60 * 60 * 24);

    // 判断是否不超过 7 天
    return daysDifference <= 7 && daysDifference >= 0;
}

function setLastWeek() { //将日期设为近7天

    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
    const startDateString = getDateTimeString(new Date(start).getTime())
    strTime.value = startDateString + ' 00:00:00'
    endTime.value = getDateTimeString(new Date().getTime()) + ' 23:59:59'
}



//上传全部离线订单
async function uploadAllOfflineOrder() {
    try {
        const data = await window.electron.ipcRenderer.invoke('select-order', '')
       // console.log(data)

        if (data.length <= 0) {
            ElMessage({
                message: '当前没有可上传的离线订单',
                type: 'warning'
            })
            return false
        }
        //console.log(data)
        let mapData = data.map(item => {
            return {
                ...item,
                memberCouponPOSDtos: JSON.parse(item.memberCouponPOSDtos),
                orderDetailAddDtos: JSON.parse(item.orderDetailAddDtos),
                orderPayDto: JSON.parse(item.orderPayDto)
            }
        })


        isShowUploadDialog.value = true
        for (let i = 0; i < mapData.length; i++) {
            try {

                currentUploadIndex.value = i + 1
                await createOrder(mapData[i])

                await window.electron.ipcRenderer.send('delete-order', mapData[i].offineID)
            } catch (error) {
               // console.log(`第 ${i + 1} 个订单上传失败:`, error);

                ElMessage({
                    message: `第 ${i + 1} 个订单上传失败: ${error.message},请稍后重试`,
                    type: 'error'
                });
            }
        }
        ElMessage({
            message: '离线订单上传完毕',
            type: 'success'
        })
        isShowUploadDialog.value = false



    } catch (error) {
        console.log(error)
    }

}


// 向下滚动
const goodsScrollDown = () => {

goodsCurrentPage.value++
goodsTableRef.value.setScrollTop((goodsCurrentPage.value - 1) * (goodsPageSize.value * 40))
};
const goodsScrollUp = () => {

    goodsCurrentPage.value--
goodsTableRef.value.setScrollTop((goodsCurrentPage.value - 1) * (goodsPageSize.value * 40))
};

//付款信息向下滚动
const payTypeScrollDown = () => {

    payTypeCurrentPage.value++
    payTypeTableRef.value.setScrollTop((payTypeCurrentPage.value - 1) * (payTypePageSize.value * 40))
};
const payTypeScrollUp = () => {

    payTypesCurrentPage.value--
    payTypeTableRef.value.setScrollTop((payTypeCurrentPage.value - 1) * (payTypePageSize.value * 40))
};


</script>
<style lang='scss'>
.custom_search_class {
    left: 0 !important;
    top: 130px !important;
    bottom: unset;
}

//手机号键盘
.custom_phone_class {
    left: 430px !important;
}


.order_desc_dialog {
    .title {
        font-size: 16px;
        padding: 10px 0;
    }

    .dialog-footer {
        display: flex;
        justify-content: space-between;
    }
}
</style>
<style lang="scss"></style>
<style scoped lang='scss'>
#app {
    overflow: hidden;
}

.main_wrap {
    padding: 0;
    overflow: hidden;
    position: relative;

    .top {
        padding: 10px;
        background-color: #fff;

        .row {
            display: flex;
            align-items: center;
            padding-top: 10px;
            background-color: #fff;

            .form_item {
                display: flex;
                align-items: center;
                margin-right: 10px;

                .label {
                    width: 80px;

                }
            }
        }
    }

    .main {
        height: calc(100% - 130px);
        overflow: hidden;
        position: relative;
        z-index: 2;
        background-color: #fff !important;

        .my_table {
            height: calc(100% - 100px);
            overflow: hidden;
            padding: 0 10px;
            background-color: #fff;

            .state_0 {
                color: var(--el-color-danger);
            }

            .state_1 {
                color: var(--el-color-success);
            }

            .state_2 {
                color: var(--el-color-info);
            }

            .state_9 {
                color: var(--el-color-warning);
            }
        }

        .bottom {
            height: 100px;

            .total {
                display: flex;
                align-items: center;
                height: 40px;
                line-height: 40px;
                text-indent: 10px;
                background-color: #fff;

                &>div {
                    margin-right: 20px;
                }
            }

            .btns {
                padding: 10px;
            }

        }
    }

}

.refund-dialog-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .left {
        display: flex;
        align-items: center;

        span {
            margin: 0 10px;
        }

    }
}

//打印相关
.print_wrap {
    .title {
        text-align: center;
        line-height: 1.5;
        font-size: 38px;
    }

    background-color: #fff;
    color: #000;
    width: 800px; //这里一定设置为600px 经过测试后的合适距离
    box-sizing:border-box;
    // font-weight: bold;
    font-size:36px;
    position: absolute;
    top: 0;
    left:0;
    z-index: -10;

    .line {
        width: 100%;
        border-top: 1px dashed #000;
        height: 1px;
        margin: 15px 0;
    }

    .margin_bottom_placeholder {
        //这里使用空div 站位 下边距
        width: 100%;
        height: 300px;

    }

    .flex {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .discount {
        text-align: right;
    }
}

.upload_dialog_main {
    font-size: 20px;
    padding: 20px 0;

    &>span {
        color: var(--el-color-success);
    }
}
.paginate_btns {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        height: 50px;
        margin-left: 5px;

        &>div {
            margin: 0 10px;
        }
    }
    .table_top{
        display: flex;
        align-items: center;
        justify-content: space-between;
    }


    .refund_dialog_main{
        :deep(.el-table__cell){
            padding: 0;
            height:40px;
        }
    }
</style>